/**
 * catchErr 拦截器是否拦截错误 true:拦截 false:不拦截
 */
import instance from './http'
import { needRefreshToken } from '@/utils/auth'
import refreshToken, { isRefreshing } from '@/utils/refreshToken'
import { refreshTokenUrl, loginUrl } from '@/config/constant'

class HttpRequest {
  baseOptions(params, method = 'post', catchErr = false) {
    const { url, data } = params
    const contentType = params.contentType || 'application/json'
    const option = {
      url,
      data,
      header: {
        'content-type': contentType,
        'X-Requested-With': 'XMLHttpRequest'
      },
      catch: catchErr
    }
    const needRefresh = this.getNeedRefreshToken(url)
    if (needRefresh) {
      return refreshToken(() => instance[method](option))
    } else {
      return instance[method](option)
    }
  }

  get(url, data = '') {
    const option = { url, data }
    return this.baseOptions(option)
  }

  post(url, data = {}, catchErr, contentType) {
    const params = { url, data, contentType }
    return this.baseOptions(params, 'post', catchErr)
  }

  put(url, data = {}) {
    const option = { url, data }
    return this.baseOptions(option, 'put')
  }

  delete(url, data = {}) {
    const option = { url, data }
    return this.baseOptions(option, 'delete')
  }

  getNeedRefreshToken(url) {
    const isNotRefreshReq = url !== refreshTokenUrl && url !== loginUrl
    const needRefresh = needRefreshToken()
    return isNotRefreshReq && (needRefresh || isRefreshing)
  }
}

export default new HttpRequest()
